<template>
    <div id="classs">
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="6">
                    <!-- 学院筛选下拉框（保留全部选项） -->
                    <el-select v-model="selectedDepartmentId"
                        placeholder="请选择学院"
                        @change="handleDepartmentChange">
                        <el-option value="" label="全部" />
                        <el-option v-for="dept in departmentOptions"
                            :key="dept.value"
                            :label="dept.label"
                            :value="dept.value" />
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <!-- 专业筛选下拉框（保留全部选项） -->
                    <el-select v-model="selectedMajorId"
                        placeholder="请选择专业"
                        @change="handleMajorChange">
                        <el-option value="" label="全部" />
                        <el-option v-for="major in majorOptions"
                            :key="major.value"
                            :label="major.label"
                            :value="major.value" />
                    </el-select>
                </el-col>
                <el-col :span="8">
                    <!-- 搜索与添加区域 -->
                    <el-input placeholder="请输入班级名称或ID"
                        v-model="queryInfo.query"
                        clearable>
                        <template #append>
                            <el-button @click="handleSearch">
                                <el-icon>
                                    <search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="addDialogVisible = true">添加班级</el-button>
                </el-col>
            </el-row>
            <!-- 班级列表区域 -->
            <el-table :data="filteredClasssList"
                :row-class-name="getRowClass"
                border
                stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="班级ID"
                    prop="classsId"></el-table-column>
                <el-table-column label="班级名称"
                    prop="classsName"
                    width="190px"></el-table-column>
                <el-table-column label="所属专业"
                    width="150">
                    <template #default="scope">
                        {{ getMajorName(scope.row.majorId) }}
                    </template>
                </el-table-column>
                <el-table-column label="所属学院"
                    width="150">
                    <template #default="scope">
                        {{ getDepartmentName(scope.row.majorId) }}
                    </template>
                </el-table-column>
                <el-table-column label="班级人数上限"
                    prop="classsSizeLimit"></el-table-column>
                <el-table-column label="班级描述"
                    prop="classsDescription"></el-table-column>
                <el-table-column label="操作"
                    width="200px">
                    <template v-slot="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary"
                            @click="showEditDialog(scope.row.classsId)">
                            <el-icon>
                                <edit />
                            </el-icon>
                        </el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger"
                            @click="handleDelete(scope.row.classsId)">
                            <el-icon>
                                <delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination v-model:current-page="queryInfo.pagenum"
                v-model:page-size="queryInfo.pagesize"
                :total="filteredTotal"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加班级对话框 -->
        <el-dialog v-model="addDialogVisible"
            title="添加班级"
            width="50%">
            <el-form :model="addForm"
                :rules="addFormRules"
                ref="addFormRef"
                label-width="80px">
                <el-form-item label="班级ID"
                    prop="classsId">
                    <el-input v-model="addForm.classsId"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="班级名称"
                    prop="classsName">
                    <el-input v-model="addForm.classsName"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="所属学院"
                    prop="departmentId">
                    <el-select v-model="addForm.departmentId"
                        placeholder="请选择学院"
                        @change="onAddDepartmentChange"
                        filterable
                        clearable>
                        <!-- 移除全部选项 -->
                        <el-option v-for="item in departmentOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属专业"
                    prop="majorId">
                    <el-select v-model="addForm.majorId"
                        placeholder="请选择专业"
                        :options="addMajorOptions"
                        filterable
                        clearable>
                        <el-option v-for="item in addMajorOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="班级人数上限"
                    prop="classsSizeLimit">
                    <el-input-number v-model="addForm.classsSizeLimit"
                        :min="1"
                        :max="100"
                        controls-position="right" />
                </el-form-item>
                <el-form-item label="班级描述"
                    prop="classsDescription">
                    <el-input v-model="addForm.classsDescription"
                        autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修改班级对话框 -->
        <el-dialog v-model="editDialogVisible"
            title="修改班级信息"
            width="50%">
            <el-form :model="editForm"
                ref="editFormRef"
                label-width="80px">
                <el-form-item label="班级ID">
                    <el-input v-model="editForm.classsId"
                        disabled /> <!-- 不可修改 -->
                </el-form-item>
                <el-form-item label="班级名称"
                    prop="classsName">
                    <el-input v-model="editForm.classsName" />
                </el-form-item>
                <el-form-item label="所属学院"
                    prop="departmentId">
                    <el-select v-model="editForm.departmentId"
                        placeholder="请选择学院"
                        @change="onEditDepartmentChange"
                        filterable
                        clearable>
                        <!-- 移除全部选项 -->
                        <el-option v-for="item in departmentOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属专业"
                    prop="majorId">
                    <el-select v-model="editForm.majorId"
                        placeholder="请选择专业"
                        :options="editMajorOptions"
                        filterable
                        clearable>
                        <el-option v-for="item in editMajorOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="班级人数上限"
                    prop="classsSizeLimit">
                    <el-input-number v-model="editForm.classsSizeLimit"
                        :min="1"
                        :max="100"
                        controls-position="right" />
                </el-form-item>
                <el-form-item label="班级描述"
                    prop="classsDescription">
                    <el-input v-model="editForm.classsDescription" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitEditForm">保存修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
/* 自定义删除动画样式 */
.deleting-row {
    animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
    from {
        opacity: 1;
        transform: translateX(0);
    }

    to {
        opacity: 0;
        transform: translateX(20px);
    }
}
</style>

<script>
import {
    getClasssList,
    addClasss,
    updateClasss,
    deleteClasss,
    getClasssDetail
} from '@/api/classs';
import { getDepartmentList } from '@/api/department';
import { getMajorList } from '@/api/major';

export default {
    data() {
        return {
            // 查询参数
            queryInfo: {
                pagenum: 1,       // 当前页码
                pagesize: 10,     // 每页显示数量
                query: '',        // 查询关键词
                orderBy: 0        // 排序方式(后端默认0)
            },
            // 原始班级列表数据
            classsList: [],
            // 过滤后的班级列表
            filteredClasssList: [],
            // 过滤后的总数据条数
            filteredTotal: 0,
            // 院系列表数据
            departmentList: [],
            // 专业列表数据
            majorList: [],
            // 专业ID到名称的映射
            majorMap: {},
            // 专业ID到学院ID的映射
            majorDepartmentMap: {},
            // 学院下拉选项
            departmentOptions: [],
            // 专业下拉选项
            majorOptions: [],
            // 当前选中的学院ID（""表示全部）
            selectedDepartmentId: "",
            // 当前选中的专业ID（""表示全部）
            selectedMajorId: "",
            // 控制对话框显示与隐藏
            addDialogVisible: false,
            editDialogVisible: false,
            // 正在删除的ID列表（用于动画）
            deletingIds: [],
            // 添加班级表单数据
            addForm: {
                classsId: "",
                classsName: "",
                departmentId: "",
                majorId: "",
                classsSizeLimit: 30,
                classsDescription: ""
            },
            // 添加表单中专业选项
            addMajorOptions: [],
            // 添加表单验证规则
            addFormRules: {
                classsId: [{ required: true, message: "请输入班级ID", trigger: "blur" }],
                classsName: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
                departmentId: [{ required: true, message: "请选择所属学院", trigger: "change" }],
                majorId: [{ required: true, message: "请选择所属专业", trigger: "change" }],
                classsSizeLimit: [{ required: true, message: "请设置班级人数上限", trigger: "blur" }],
                classsDescription: [{ required: true, message: "请输入班级描述", trigger: "blur" }]
            },
            // 编辑班级表单数据
            editForm: {
                classsId: "",
                classsName: "",
                departmentId: "",
                majorId: "",
                classsSizeLimit: 30,
                classsDescription: ""
            },
            // 编辑表单中专业选项
            editMajorOptions: [],
            // 编辑表单验证规则
            editFormRules: {
                classsName: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
                departmentId: [{ required: true, message: "请选择所属学院", trigger: "change" }],
                majorId: [{ required: true, message: "请选择所属专业", trigger: "change" }],
                classsSizeLimit: [{ required: true, message: "请设置班级人数上限", trigger: "blur" }],
                classsDescription: [{ required: true, message: "请输入班级描述", trigger: "blur" }]
            }
        };
    },
    created() {
        // 初始化数据
        this.fetchDepartments();
        this.fetchClasssList();
    },
    computed: {
        // 计算过滤后的班级列表和总数
        filteredClasssAndTotal() {
            if (!this.classsList || this.classsList.length === 0) {
                return { list: [], total: 0 };
            }
            
            // 筛选条件：
            // 1. 班级专业属于所选学院（当选择具体学院时）
            // 2. 班级专业等于所选专业（当选择具体专业时）
            let filteredList = this.classsList;
            
            // 应用学院筛选
            if (this.selectedDepartmentId !== "") {
                filteredList = filteredList.filter(classs => {
                    const majorDepartmentId = this.majorDepartmentMap[classs.majorId];
                    return majorDepartmentId === this.selectedDepartmentId;
                });
            }
            
            // 应用专业筛选
            if (this.selectedMajorId !== "") {
                filteredList = filteredList.filter(classs => {
                    return classs.majorId === this.selectedMajorId;
                });
            }
            
            // 应用搜索条件
            if (this.queryInfo.query) {
                const query = this.queryInfo.query.toLowerCase();
                filteredList = filteredList.filter(classs => {
                    return classs.classsId.toLowerCase().includes(query) || 
                           classs.classsName.toLowerCase().includes(query);
                });
            }
            
            // 计算分页数据
            const start = (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize;
            const end = start + this.queryInfo.pagesize;
            const pagedList = filteredList.slice(start, end);
            
            return {
                list: pagedList,
                total: filteredList.length
            };
        }
    },
    methods: {
        // 获取过滤后的班级列表和总数
        getFilteredData() {
            const { list, total } = this.filteredClasssAndTotal;
            this.filteredClasssList = list;
            this.filteredTotal = total;
        },

        // 获取院系列表
        async fetchDepartments() {
            try {
                const res = await getDepartmentList(
                    this.queryInfo.pagenum,
                    this.queryInfo.pagesize,
                    this.queryInfo.orderBy,
                    {} // 空请求体获取所有学院
                );

                if (res.code === 200) {
                    this.departmentList = res.data.list || [];
                    this.departmentOptions = this.departmentList.map(item => ({
                        value: item.departmentId,
                        label: item.departmentName
                    }));
                    
                    // 默认选择全部
                    this.selectedDepartmentId = "";
                    // 加载所有专业
                    this.fetchMajorsByDepartment("");
                } else {
                    this.$message.error(res.message || '获取院系列表失败');
                }
            } catch (error) {
                console.error('获取院系列表失败:', error);
                this.$message.error('获取院系列表失败，请稍后再试');
            }
        },

        // 根据学院ID获取专业列表
        async fetchMajorsByDepartment(departmentId) {
            try {
                let requestBody = {};
                // 如果不是全部选项，添加学院ID过滤
                if (departmentId !== "") {
                    requestBody = {
                        departmentId: departmentId
                    };
                }

                const res = await getMajorList(
                    this.queryInfo.pagenum,
                    this.queryInfo.pagesize,
                    this.queryInfo.orderBy,
                    requestBody
                );

                if (res.code === 200) {
                    this.majorList = res.data.list || [];
                    this.majorMap = this.majorList.reduce((map, item) => {
                        map[item.majorId] = item.majorName;
                        return map;
                    }, {});
                    
                    // 构建专业到学院的映射
                    this.majorDepartmentMap = this.majorList.reduce((map, item) => {
                        map[item.majorId] = item.departmentId;
                        return map;
                    }, {});
                    
                    // 专业选项直接使用API返回的数据，不添加"全部"选项
                    this.majorOptions = this.majorList.map(item => ({
                        value: item.majorId,
                        label: item.majorName
                    }));
                    
                    // 默认选择全部
                    this.selectedMajorId = "";
                    
                    // 刷新班级列表
                    this.fetchClasssList();
                } else {
                    this.$message.error(res.message || '获取专业列表失败');
                }
            } catch (error) {
                console.error('获取专业列表失败:', error);
                this.$message.error('获取专业列表失败，请稍后再试');
            }
        },

        // 获取班级列表
        async fetchClasssList() {
            try {
                // 构建请求体参数（不包含学院和专业过滤，前端处理）
                const requestBody = {
                    classsName: this.queryInfo.query
                };

                const res = await getClasssList(
                    this.queryInfo.pagenum,
                    this.queryInfo.pagesize,
                    this.queryInfo.orderBy,
                    requestBody
                );

                if (res.code === 200) {
                    this.classsList = res.data.list || [];
                    // 应用过滤
                    this.getFilteredData();
                } else {
                    this.$message.error(res.message || '获取班级列表失败');
                }
            } catch (error) {
                console.error('获取班级列表失败:', error);
                this.$message.error('获取班级列表失败，请稍后再试');
            }
        },

        // 处理学院选择变化
        async handleDepartmentChange() {
            // 重置页码和专业选择
            this.queryInfo.pagenum = 1;
            this.selectedMajorId = "";
            // 根据选择的学院加载专业
            await this.fetchMajorsByDepartment(this.selectedDepartmentId);
        },

        // 处理专业选择变化
        handleMajorChange() {
            // 重置页码
            this.queryInfo.pagenum = 1;
            // 应用过滤
            this.getFilteredData();
        },

        // 处理搜索
        handleSearch() {
            this.queryInfo.pagenum = 1; // 重置页码
            this.fetchClasssList();
        },

        // 添加表单中学院变化时更新专业选项
        onAddDepartmentChange() {
            this.updateMajorOptions('add');
        },

        // 编辑表单中学院变化时更新专业选项
        onEditDepartmentChange() {
            this.updateMajorOptions('edit');
        },

        // 更新专业选项
        updateMajorOptions(formType) {
            const departmentId = formType === 'add' 
                ? this.addForm.departmentId 
                : this.editForm.departmentId;
                
            let options = [];
            if (departmentId === "") {
                // 全部选项，显示所有专业
                options = this.majorList.map(major => ({
                    value: major.majorId,
                    label: major.majorName
                }));
            } else {
                // 按学院筛选专业
                options = this.majorList
                    .filter(major => major.departmentId === departmentId)
                    .map(major => ({
                        value: major.majorId,
                        label: major.majorName
                    }));
            }
            
            // 更新专业选项
            if (formType === 'add') {
                this.addMajorOptions = options;
                // 设置默认值为第一个专业（如果有）
                this.addForm.majorId = options.length > 0 ? options[0].value : "";
            } else {
                this.editMajorOptions = options;
                // 设置默认值为第一个专业（如果有）
                this.editForm.majorId = options.length > 0 ? options[0].value : "";
            }
        },

        // 获取专业名称（处理未知专业）
        getMajorName(majorId) {
            if (majorId === "" || majorId === null) {
                return "未知专业";
            }
            return this.majorMap[majorId] || "未知专业";
        },

        // 获取学院名称（通过专业ID）
        getDepartmentName(majorId) {
            if (majorId === "" || majorId === null) {
                return "未知学院";
            }
            const departmentId = this.majorDepartmentMap[majorId];
            if (!departmentId) return "未知学院";
            
            const department = this.departmentList.find(d => d.departmentId === departmentId);
            return department ? department.departmentName : "未知学院";
        },

        // 显示编辑对话框
        async showEditDialog(classsId) {
            try {
                // 获取班级详情
                const res = await getClasssDetail(classsId);
                if (res.code === 200) {
                    this.editForm = res.data;
                    
                    // 设置学院和专业下拉框
                    this.editForm.departmentId = String(this.editForm.departmentId);
                    this.editForm.majorId = String(this.editForm.majorId);
                    
                    // 更新专业选项
                    this.updateMajorOptions('edit');
                    
                    this.editDialogVisible = true;
                } else {
                    this.$message.error(res.message || '获取班级详情失败');
                }
            } catch (error) {
                console.error('获取班级详情失败:', error);
                this.$message.error('获取班级详情失败，请稍后再试');
            }
        },

        // 提交添加表单
        async submitAddForm() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await addClasss(this.addForm);
                        if (res.code === 200) {
                            this.$message.success('添加班级成功');
                            this.addDialogVisible = false;
                            this.fetchClasssList();
                            // 重置表单
                            this.$nextTick(() => {
                                this.$refs.addFormRef.resetFields();
                            });
                        } else {
                            this.$message.error(res.message || '添加班级失败');
                        }
                    } catch (error) {
                        console.error('添加班级失败:', error);
                        this.$message.error('添加班级失败，请稍后再试');
                    }
                }
            });
        },

        // 提交编辑表单
        async submitEditForm() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await updateClasss(this.editForm);
                        if (res.code === 200) {
                            this.$message.success('修改班级成功');
                            this.editDialogVisible = false;
                            this.fetchClasssList();
                        } else {
                            this.$message.error(res.message || '修改班级失败');
                        }
                    } catch (error) {
                        console.error('修改班级失败:', error);
                        this.$message.error('修改班级失败，请稍后再试');
                    }
                }
            });
        },

        // 处理删除
        async handleDelete(classsId) {
            try {
                // 添加删除动画标记
                this.deletingIds.push(classsId);

                // 确认删除
                await this.$confirm(
                    '确认删除该班级? 此操作不可恢复',
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );

                // 调用删除API
                const res = await deleteClasss(classsId);
                if (res.code === 200) {
                    this.$message.success('删除班级成功');
                    this.fetchClasssList();
                } else {
                    this.$message.error(res.message || '删除班级失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除班级失败:', error);
                    this.$message.error('删除班级失败，请稍后再试');
                }
            } finally {
                // 移除动画标记
                this.deletingIds = this.deletingIds.filter(id => id !== classsId);
            }
        },

        // 获取删除行样式
        getRowClass({ row }) {
            return this.deletingIds.includes(row.classsId) ? 'deleting-row' : '';
        }
    },
    // 监听数据变化，重新计算过滤结果
    watch: {
        classsList() {
            this.getFilteredData();
        },
        selectedDepartmentId() {
            this.getFilteredData();
        },
        selectedMajorId() {
            this.getFilteredData();
        },
        queryInfo: {
            query: {
                handler() {
                    this.queryInfo.pagenum = 1;
                    this.fetchClasssList();
                },
                deep: true
            }
        }
    },
    // 对话框打开时刷新数据
    watch: {
        addDialogVisible(newVal) {
            if (newVal) {
                // 重置表单数据
                this.addForm = {
                    classsId: "",
                    classsName: "",
                    departmentId: this.departmentOptions.length > 0 ? this.departmentOptions[0].value : "", // 默认选择第一个学院
                    majorId: "", // 初始为空，将在updateMajorOptions中设置默认值
                    classsSizeLimit: 30,
                    classsDescription: ""
                };
                
                // 初始化专业选项
                this.$nextTick(() => {
                    // 确保DOM更新后再调用
                    this.updateMajorOptions('add');
                });
            }
        }
    }
};
</script>


